package controller;

/**
 * The LobbyController provides all the methods needed to update the LobbyDisplay class
 * and receive input from it. It acts as an intermediate between the lobby GUI and the server.
 */
import gui.Display;
import gui.LobbyDisplay;

import java.rmi.RemoteException;
import java.util.ArrayList;

import model.TableSettings;
import java.sql.*;

public class LobbyController extends Controller {
	/**
	 * Constructor method. Initialises the LobbyDisplay by passing the previous Display object
	 * and calls the setDisplay field.
	 * @param display The previous Display object.
	 */
	
	public LobbyController(Display display) {
		LobbyDisplay lobbyDisplay = new LobbyDisplay(this, display);
		setDisplay(lobbyDisplay);
	}

	/**
	 * Display the login screen by giving control to the login controller
	 */
	public void returnToLogin() {
		Controller loginController = new LoginController(display);
		this.giveControlTo(loginController);
	}
	
	/**
	 * Add the player to the specific table
	 * Display the game screen by giving control to the game controller
	 * @param tableID identification number of the table to be joined
	 * @param chips number of chips the player will bring in to the new table
	 * @throws RemoteException
	 */
	public void joinGame(int tableID, int chips) throws RemoteException {
		
		Controller gameController = new GameController(display);
		this.giveControlTo(gameController);
		((GameController)gameController).setTableID(tableID);
		((GameController)gameController).sendCallback(tableID);
		serverRemote.addPlayerToTable(tableID, user.getUsername(), chips);
		((GameController)gameController).refreshTable(tableID);
		((GameController)gameController).sendMessage("--> " + user.getUsername() + "has joined the table with $" + chips);
		
	}
	
	/**
	 * If the max number of tables have not been reached,
	 * Create a new table with given settings and add the creator to the table.
	 * Display the game screen by giving control to the game controller
	 * @param tableSettings the settings for the newly created table
	 * @param chips number of chips the player will bring in to the new table
	 * @throws RemoteException
	 */
	public void createGame(TableSettings tableSettings, int chips) throws RemoteException {		
		int tableID = 0;
		
		try {	
			tableID = serverRemote.createTable(tableSettings);
			if (tableID == 0) {
				display.showError("Max number of tables on server has been reached.");
			}
			else {
				Controller gameController = new GameController(display);
				this.giveControlTo(gameController);
				((GameController)gameController).setTableID(tableID);
				((GameController)gameController).sendCallback(tableID);
				serverRemote.addPlayerToTable(tableID, user.getUsername(), chips);
				((GameController)gameController).refreshTable(tableID);
				((GameController)gameController).setOwner(user.getUsername());
			}
		} 
		catch (RemoteException e) {	
			e.printStackTrace();
		}		
	}
	
	/**
	 * Display the statistics page by giving control to the Statistics Controller
	 */
	public void openStatistics(){
		Controller statisticsController = new StatisticsController(display);
		this.giveControlTo(statisticsController);
		((StatisticsController) statisticsController).initializeDisplay(display);
	}
	
	/**
	 * Display the settings page by giving control to the Statistics Controller
	 */
	public void openSettings() {
		Controller settingsController = new SettingsController();
		this.giveControlTo(settingsController);
		((SettingsController) settingsController).initializeDisplay(display);
	}
	
	/**
	 * Create a table by calling the the createTable method of the server remote
	 * @throws RemoteException
	 */
	public void createTable() throws RemoteException {
		serverRemote.createTable(new TableSettings("Table created"));	
	}
	
	/**
	 * The refreshTables returns a string array of the list of tables currently being
	 * hosted on the server as well as relevant table information, such as max players
	 * and current number of players.
	 * @return A string array of the list of tables and their relevant information 
	 * returned by the server.
	 * @throws RemoteException
	 */
	public String[] refreshTables() throws RemoteException {
		ArrayList<Integer> ids = serverRemote.getTableIDs();	
		int numTables = serverRemote.getNumTables();
		String[] tableIDs = new String[ids.size()];
		TableSettings[] ts = new TableSettings[ids.size()]; 

		for(int j=0; j<ids.size(); j++) {
			tableIDs[j] = ids.get(j).toString();			
			ts[j] = serverRemote.getTableSettings(j+1);
		}
		
		String[] tableData = new String[numTables];
				
		for(int i=0; i<numTables; i++) {
				try {
					String temp = ts[i].getName();
					int spaces = 15 - temp.length();
					
					tableData[i] = "" + ts[i].getName();
					for (int j = 0; j < spaces; j++) {
						tableData[i] += " ";
					}
					tableData[i] += "Players: " + (ts[i].getMaxPlayers()-serverRemote.getTableFreeSlots(i+1)) + "/" + ts[i].getMaxPlayers();
					tableData[i] += "               Ante: " + ts[i].getAnte();
					
					if(ts[i].getMaxBet() == 0) {
						tableData[i] += "               Max Bet: Unlimited";
					}
					else {
						tableData[i] += "               Max Bet: " + ts[i].getMaxBet();
					}
				}
					
				catch(NullPointerException e) {
					String temp = ts[i].getName();
					int spaces = 15 - temp.length();
					
					tableData[i] = "" + ts[i].getName();
					for (int j = 0; j < spaces; j++) {
						tableData[j] += " ";
					}
					
					tableData[i] += "Free Slots: N/A";
					tableData[i] += "               Ante: " + ts[i].getAnte();
					if(ts[i].getMaxBet() == 0) {
						tableData[i] += "               Max Bet: Unlimited";
					}
					else {
						tableData[i] += "               Max Bet: " + ts[i].getMaxBet();
					}					
					
				}
			
		}		
		return tableData;
	}
	
	// TODO: KEVIN FILL THIS SHIT IN.
	public String[] getFriendsList()
	{
		try {
			Statement stmt;
			ResultSet rs;
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			String url = "jdbc:mysql://instance10905.db.xeround.com:7414/fcsgroup2"; //Location of Database
			
			//Connect to the Database
			Connection con = DriverManager.getConnection(url,"fcsgroup2", "qwerty123");

			System.out.println("URL: " + url);
			System.out.println("Connection: " + con);
			
			//Get a Statement Object
			stmt = con.createStatement();
			
			String update = "SELECT Friend1, Friend2, Friend3, Friend4, Friend5, Friend6, Friend7, Friend8, Friend9, "
					+"Friend10, Friend11, Friend12, Friend13, Friend14, Friend15, Friend16, Friend17, Friend18, Friend19, "
					+"Friend20 from social WHERE Username='"+user.getUsername()+"'";
			rs = stmt.executeQuery(update);
			
			String friends[] = new String[20];
			
			rs.next();
			
			for(int i=1;i<=20;i++) {
				friends[i-1] = rs.getString("Friend"+i);
			}
			//Close the connection
			con.close();
			stmt.close();
			return friends;
		}
		catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * Add chips to the users credit if the user has less than 500 chips
	 * Update the database if chips are added
	 * @param chips amount of chips to be added to the user's bank
	 * @return true if chips were added, false otherwise
	 */
	public boolean addCredit(int chips){
		  if(user.getUserBank().getBalance() >= 500){
		   return false;
		  }
		  else{
		   user.getUserBank().deposit(this.getUser().getUsername(),chips);
		   return true;
		  } 
		 }
}
